import React from 'react';
import {
    Row,
    Col,
    Table,
    Icon,
    Menu,
    Dropdown,
    Button,
    Modal,
    notification,
    Form,
    Tooltip,
    Switch,
    Popconfirm,
    AutoComplete,
} from 'antd';
import axios from 'axios';
import { config } from 'utils';
import { Input } from 'antd';
import intercept from '../../utils/intercept';
import '../BusStation/less/common.less';
import '../BusStation/less/CustomLine.less';
//import { Map, Marker, NavigationControl, InfoWindow } from 'react-bmap';
const Search = Input.Search;
const FormItem = Form.Item;
const Option = AutoComplete.Option;

class CustomDriver extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            loading: false,
            pagination: {
                current: 1,
                pagesize: 10
            },
            onChange: this.onChange,
            formVisiable: false,
            isEnable: false,
            formTitle: '编辑司机信息',
            formSex: 1,
            userOrgans: ['省联网', '郑州市'],
            organNameValid:'',
            key:''
        }
    };

    getDriverInfo = (params = {}) => {
        const token = sessionStorage.getItem("token");
        this.setState({ loading: true });
        axios
            .get(`${config.api}BasicInfo/QueryDriverInfo?Page=${params.page}&&PageSize=${this.state.pagination.pageSize}&key=${params.key}`, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            })
            .then((data) => {
                console.log(data);
                const pagination = {
                    ...this.state.pagination
                };
                pagination.total = data.data.pageList.totalRows;
                pagination.current = params.page;
                this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination });
            }).catch(err => {
                intercept;
            });
    }

    openNotification = (title, desc, color) => {
        notification.open({
            message: title,
            description: desc,
            icon: <Icon type="smile-circle" style={{ color: color }} />,
        });
    };

    handleReset = () => {
        this
            .props
            .form
            .resetFields();
        this.setState({
            organNameValid:'',
            formSex: 1,
        })
    }

    onChange = (pagination, filters, sorter) => {
        this.getDriverInfo({
            sortField: sorter.field,
            sortOrder: sorter.order,
            page: pagination.current,
            key:this.state.key,
            ...filters
        });
        this.setState({
            sortedInfo: sorter,
        });
    };

    componentDidMount() {
        this.getDriverInfo({key:''});
        this.getUserOrgans();
    };

    handleCancel = () => {
        this.setState({
            formVisiable: false
        })
    }

        // 搜索
        search(value) {
            this.setState({
                key:value
            })
            this.getDriverInfo({ key: value });
        }

    driverForm = (ev, record) => {
        //console.log(record);
        this.props.form
            .setFieldsValue({
                driverId: record.driverId,
                driverName: record.driverName,
                //sex: record.sex,
                phoneNumber: record.phoneNumber,
                cardId: record.cardId,
                organName: record.organName,
                drivingLicence: record.drivingLicence,
            });

        this.setState({
            isEnable: record.isEnable,
            formVisiable: true,
            formSex: record.sex == "男" ? 1 : 0,
            formTitle:"编辑司机信息",
        })
    }

    addDriverForm = () => {
        this.handleReset();
        this.setState({
            formVisiable: true,
            isEnable: false,
            formTitle: '录入司机信息',
            formSex: 1,
        });
        this.props.form
            .setFieldsValue({
                driverId: -1
            });
    }

    editDriverEnable = (checked, record) => {
        this.setState({ loading: true });
        const token = sessionStorage.getItem("token");
        let dataSource = this.state.dataSource;
        for (let i = 0; i < dataSource.length; i++) {
            if (dataSource[i].driverId == record.driverId) {
                dataSource[i].isEnable = checked;
            }
        }

        axios
            .post(`${config.api}BasicInfo/EditDriverInfo`, { editType: 3, driverId: record.driverId, isEnable: record.isEnable,organName:record.organName }, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                if (data.data.result) {
                    this.openNotification("状态修改", checked ? "启用成功" : "禁用成功", "#108ee9");
                }
                else {
                    this.openNotification("修改状态失败", data.data.errorMessage, "red");
                    for (let i = 0; i < dataSource.length; i++) {
                        if (dataSource[i].driverId == record.driverId) {
                            dataSource[i].isEnable = !checked;
                        }
                    }
                }
                this.setState({ loading: false, dataSource });
            }).catch(err => {
                intercept;
            });
    }

    deleteDriver = (record) => {
        const token = sessionStorage.getItem("token");
        this.setState({ loading: true });
        axios
            .post(`${config.api}BasicInfo/EditDriverInfo`, { editType: 4, driverId: record.driverId }, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            })
            .then((data) => {
                if (data.data.result) {
                    this.handleReset();
                    this.getDriverInfo();
                    this.openNotification("删除司机", "删除司机成功", "#108ee9");
                } else {
                    this.openNotification("删除司机失败", data.data.errorMessage, "red");
                    this.setState({ loading: false });
                }
            }).catch(err => {
                intercept;
            });
    }

    getUserOrgans = () => {
        const token = sessionStorage.getItem("token");
        axios
            .get(`${config.api}User/GetOrgansKey`, {
                headers: {
                    Authorization: 'Bearer ' + token
                }
            })
            .then((res) => {
                let tmp = res
                    .data
                    .userOrgans
                    .map(m => (
                        <Option key={m.key} value={m.label}>
                            {m.label}
                        </Option>
                    ));
                this.setState({ userOrgans: tmp });
            }).catch(err => {
                intercept;
            });
    }

    editDriver = (e) => {
        e.preventDefault();
        let driverId = this.props.form.getFieldValue('driverId');
        this
            .props
            .form
            .validateFieldsAndScroll((err, values) => {
                if (!err) {
                    this.setState({ loading: true });
                    const token = sessionStorage.getItem("token");
                    let editType = 2;
                    if (driverId < 0) {
                        editType = 1;
                    }
                    let postdata = {
                        editType: editType,
                        driverId: values.driverId,
                        driverName: values.driverName,
                        sex: this.state.formSex,
                        phoneNumber: values.phoneNumber,
                        cardId: values.cardId,
                        drivingLicence: values.drivingLicence,
                        organName: values.organName,
                        isEnable: this.state.isEnable,
                    }
                    axios
                        .post(`${config.api}BasicInfo/EditDriverInfo`, postdata, {
                            headers: {
                                Authorization: 'Bearer ' + token
                            }
                        })
                        .then((data) => {
                            if (data.data.result) {
                                //this.openNotification("编辑线路", "修改线路信息成功", "#108ee9");
                                this.setState({ formVisiable: false });
                                this
                                    .props
                                    .form
                                    .resetFields();

                                let dataSource = this.state.dataSource;
                                let response = dataSource.filter(m => m.driverId == data.data.driverInfo.driverId);
                                //console.log(response);
                                //新增
                                if (response.length <= 0) {
                                    dataSource.unshift(data.data.driverInfo);
                                    this.openNotification("录入司机", "录入司机信息成功", "#108ee9");
                                }
                                //编辑
                                else {
                                    for (let i = 0; i < dataSource.length; i++) {
                                        if (dataSource[i].driverId == data.data.driverInfo.driverId) {
                                            dataSource[i] = data.data.driverInfo;
                                        }
                                    }
                                    this.openNotification("编辑司机", "修改司机信息成功", "#108ee9");
                                }
                                this.setState({
                                    dataSource,
                                });
                            } else {
                                this.openNotification("修改司机信息失败", data.data.errorMessage, "red");
                            }
                            this.setState({ loading: false });
                        }).catch(err => {
                            intercept;
                        });
                }
            });

    }

    formSex = () => {
        //console.log("value")
        this.setState({
            formSex: 0
        })
    }

    sexMenu = () => {
        return (
            <Menu onClick={this.SwitchSex}>
                <Menu.Item key="1"><span>男</span></Menu.Item>
                <Menu.Item key="0"><span>女</span></Menu.Item>
            </Menu>
        )
    }

    SwitchSex = (e) => {
        //console.log(e);
        this.setState({
            formSex: e.key
        })
    }

    onSwitchChange = (checked, type) => {
        if (type == 1) {
            this.setState({
                isUpPoint: !checked,
            });
        } else {
            this.setState({
                isEnable: !checked
            });
        }
    }

    organNameValid = (rule, value, callback) => {
        //console.log("userOrgans:", JSON.stringify(this.state.userOrgans));
        //console.log("value:", value);
        let tem = this.state.userOrgans.filter(m => m.props.value == value);
        //console.log("tem:", tem.length);
        if (tem.length > 0) {
            this.setState({
                organNameValid:'success',
            })
        }
        else{
            this.setState({
                organNameValid:'error',
            })
        }

        callback();
    }

    render() {
        let sortedInfo = this.state.sortedInfo || {};
        const columns = [
            {
                title: '姓名',
                dataIndex: 'driverName',
                width: 100
            },
            {
                title: '性别',
                dataIndex: 'sex',
                width: 50
            },
            {
                title: '电话',
                dataIndex: 'phoneNumber',
                width: 100
            },
            {
                title: '身份证号',
                dataIndex: 'cardId',
                width: 150
            },
            {
                title: '所属公司',
                dataIndex: 'organName',
                width: 100,
            },
            {
                title: '是否启用',
                dataIndex: 'isEnable',
                width: 100,
                render: (text, record) => {
                    return (<Switch
                        checkedChildren="开"
                        unCheckedChildren="关"
                        onChange={(checked, values) => {
                            this.editDriverEnable(checked, record)
                        }}
                        checked={record.isEnable}
                    />)
                }
            },
            {
                title: '操作',
                key: 'operation',
                width: 150,
                render: (text, record) => {
                    return (
                        <div>
                            <span><Button type="primary" onClick={(ev, data) => { this.driverForm(ev, record) }}>编辑</Button></span>
                            <span style={{ visibility: 'hidden' }}>藏</span>
                            <span>
                                <Popconfirm placement="top" title={"确定要删除该司机吗？"} onConfirm={(data) => this.deleteDriver(record)} okText="确定" cancelText="取消">
                                    <Button type="danger" ghost>删除</Button>
                                </Popconfirm>
                            </span>
                        </div>
                    )
                }
            },
        ];

        const { getFieldDecorator } = this.props.form;
        const className = "components-table-demo-nested";
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 6
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                }
            }
        };

        return (
            <div>
                <Row gutter={8} style={{
                    //marginTop: '10px'
                }}>
                    <Col span={2}></Col>
                    <Col span={20}>
                        <div
                            style={{
                                margin: 10
                            }}>
                            <Search
                                placeholder="请输入任意查询条件"
                                style={{
                                    width: 600
                                }}
                                onSearch={value => this.search(value)}
                            />
                            <Button type="primary" style={{ float: 'right' }} onClick={this.addDriverForm}>新增司机</Button>
                        </div>
                        <Table
                            rowKey={record => record.driverId}
                            {...this.state}
                            bordered={true}
                            className={className}
                            columns={columns}
                            style={{ background: 'white' }}                            
                        />
                    </Col>
                    <Col span={2}></Col>
                </Row>
                <Modal
                    title={this.state.formTitle}
                    width={500}
                    visible={this.state.formVisiable}
                    footer={null}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                >
                    <Form onSubmit={(e, type) => this.editDriver(e)} className="ant-advanced-search-form">
                        <FormItem
                            style={{ display: 'none' }}
                            {...formItemLayout}
                            label={(
                                <span>
                                    司机ID
                                    <Tooltip title="自动填充">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('driverId', {
                                rules: [
                                    {
                                        required: false,
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    司机姓名
                                    <Tooltip title="自动填充">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('driverName', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入站点名称',
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    性别
                                    <Tooltip title="自动填充">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback>
                            {(<Dropdown overlay={this.sexMenu()}>
                                <Button>
                                    <span>{this.state.formSex == 1 ? "男" : "女"}</span>
                                    <Icon type="down" />
                                </Button>
                            </Dropdown>)}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    手机号
                                    <Tooltip title="自动填充">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('phoneNumber', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入正确的手机号',
                                        len: 11,
                                        max: 11,
                                    }
                                ]
                            })(<Input type="phone" />)}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    身份证号
                                    <Tooltip title="自动填充">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback>
                            {getFieldDecorator('cardId', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入正确的身份证号',
                                        pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$|(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$))/,
                                    }
                                ]
                            })(<Input />)}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    所属公司
                                    <Tooltip title="">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback
                            validateStatus={this.state.organNameValid}>
                            {getFieldDecorator('organName', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择所属单位',
                                    },
                                    {
                                        validator: this.organNameValid,
                                    }
                                ]
                            })(<AutoComplete
                                dataSource={this.state.userOrgans}
                                filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} />)}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    驾驶证编号
                                    <Tooltip title="">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                        >
                            {getFieldDecorator('drivingLicence', {
                                rules: [
                                    {
                                        required: false,
                                        message: '',
                                    }
                                ]
                            })(<Input />)
                            }
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={(
                                <span>
                                    是否启用
                                    <Tooltip title="">
                                        <Icon type="question-circle-o" />
                                    </Tooltip>
                                </span>
                            )}
                            hasFeedback>
                            {(<Switch checkedChildren="启用"
                                unCheckedChildren="禁用"
                                checked={this.state.isEnable}
                                onChange={(checked, type) => {
                                    this.onSwitchChange(this.state.isEnable, 2)
                                }}
                            />)}
                        </FormItem>
                        <Row>
                            <Col span={24}>
                                <FormItem className="center">
                                    <Button onClick={this.handleReset}>重置</Button>{' '}
                                    <Button type="primary" htmlType="submit">确定</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            </div>
        )
    }
}

const CustomDriverInfo = Form.create()(CustomDriver);
export default CustomDriverInfo
